<template>
  <div class="container">
    <div class="form-container">
      <h2>零件管理</h2>
      <el-form 
        :model="form" 
        :rules="rules" 
        ref="formRef"
        label-width="120px"
        @submit.prevent
      >
        <el-form-item label="零件ID" prop="id">
          <el-input-number
            v-model="form.id"
            :min="1"
            :precision="0"
            controls-position="right"
            placeholder="请输入ID"
          ></el-input-number>
        </el-form-item>

        <el-form-item label="长度(mm)" prop="length">
          <el-input-number
            v-model="form.length"
            :min="0.01"
            :precision="2"
            :step="0.1"
            placeholder="请输入长度"
          ></el-input-number>
        </el-form-item>

        <el-form-item label="数量" prop="num">
          <el-input-number
            v-model="form.num"
            :min="1"
            :precision="0"
            placeholder="请输入数量"
          ></el-input-number>
        </el-form-item>

        <el-form-item>
          <el-button 
            type="primary" 
            @click="handleSubmit('add')"
            :loading="loading.add"
          >新增</el-button>
          <el-button 
            type="warning" 
            @click="handleSubmit('update')"
            :loading="loading.update"
          >更新</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>

      <el-divider></el-divider>
      
      <el-table :data="parts" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="120" sortable></el-table-column>
        <el-table-column prop="length" label="长度(mm)" width="150">
          <template #default="{row}">
            {{ Number(row.length).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="num" label="数量"></el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="{row}">
            <el-button size="small" @click="editPart(row)">编辑</el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="deletePart(row)"
              :loading="loading.delete === row.id"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const api = axios.create({
  baseURL: '/oneDimension',
  headers: {
    'Content-Type': 'application/json'
  }
})

// 响应式数据
const form = reactive({
  id: null,
  length: null,
  num: null
})

const parts = ref([])
const loading = reactive({
  add: false,
  update: false,
  delete: null
})

// 表单验证规则
const rules = {
  id: [
    { required: true, message: '必填项', trigger: 'blur' },
    { 
      validator: (_, v) => Number.isInteger(v) && v > 0,
      message: '必须为正整数',
      trigger: 'blur'
    }
  ],
  length: [
    { required: true, message: '必填项', trigger: 'blur' },
    { 
      validator: (_, v) => v > 0,
      message: '必须大于0',
      trigger: 'blur'
    }
  ],
  num: [
    { required: true, message: '必填项', trigger: 'blur' },
    { 
      validator: (_, v) => Number.isInteger(v) && v > 0,
      message: '必须为正整数',
      trigger: 'blur'
    }
  ]
}

// 统一处理请求响应
const handleApiResponse = (response, successMessage) => {
  if (response.data.code === 200) {
    ElMessage.success(successMessage)
    return true
  }
  ElMessage.error(response.data.msg || '操作失败')
  return false
}

// 新增/更新零件
const handleSubmit = async (action) => {
  try {
    await formRef.value.validate()
    loading[action] = true
    
    const payload = {
      id: Number(form.id),
      length: Number(form.length),
      num: Number(form.num)
    }

    let response
    switch(action) {
      case 'add':
        response = await api.post('/part/add', payload)
        if (handleApiResponse(response, '新增成功')) {
          parts.value.push({...payload})
          resetForm()
        }
        break
      case 'update':
        response = await api.put('/part/update', payload)
        if (handleApiResponse(response, '更新成功')) {
          const index = parts.value.findIndex(p => p.id === payload.id)
          if (index !== -1) parts.value.splice(index, 1, {...payload})
        }
        break
    }
  } catch (error) {
    handleError(error)
  } finally {
    loading[action] = false
  }
}

// 删除零件（严格遵循OpenAPI规范）
const deletePart = async (row) => {
  try {
    loading.delete = row.id
    
    // 根据OpenAPI文档构造请求体
    const payload = {
      id: row.id,
      length: null,  // 文档要求字段存在但可为null
      num: null      // 文档要求字段存在但可为null
    }

    const response = await api.delete('/part/delete', { data: payload })
    if (handleApiResponse(response, '删除成功')) {
      parts.value = parts.value.filter(p => p.id !== row.id)
    }
  } catch (error) {
    handleError(error)
  } finally {
    loading.delete = null
  }
}

// 错误处理
const handleError = (error) => {
  const message = error.response?.data?.msg || 
                 error.message || 
                 '请求失败，请检查：\n1. 后端服务状态\n2. 网络连接\n3. 代理配置'
  ElMessage.error(message)
  console.error('API请求错误:', error)
}

// 编辑零件
const editPart = (row) => {
  form.id = row.id
  form.length = row.length
  form.num = row.num
}

// 重置表单
const resetForm = () => {
  formRef.value.resetFields()
}

const formRef = ref(null)
</script>

<style scoped>
.container {
  max-width: 1000px;
  margin: 20px auto;
  padding: 20px;
}

.form-container {
  background: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.el-input-number {
  width: 100%;
}

.el-table {
  margin-top: 24px;
}

.el-divider {
  margin: 24px 0;
}

.el-button + .el-button {
  margin-left: 12px;
}
</style>